package cn.geekyspace.scanhive.infrastructure.plc;

import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.OutputStream;
import java.util.Arrays;

/**
 * 模拟PLC发送数据
 * 先通过 com0com 建立两个虚拟串口COM1-COM2
 * 使用COM1发送数据，程序连接COM2，接收数据
 * 程序下载地址：https://sourceforge.net/projects/com0com/
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "mock.plc", name = "enabled", havingValue = "true", matchIfMissing = false)
public class MockPLCDataSender {

    private static final String PORT_NAME = "COM1"; // 串口名称
    private static final byte[] DATA_TO_SEND = new byte[]{(byte)0x7D, (byte)0x00, (byte)0x7E, (byte)0x00, (byte)0x7F, (byte)0x00, (byte) (byte)0x80, (byte)0x00, (byte) (byte)0x81, (byte)0x00, (byte)0x1E, (byte)0x00}; // 要发送的数据

    @Scheduled(fixedRate = 10000)  // 每 10 秒执行一次
    public void sendDataToSerialPort() {
        SerialPort port = SerialPort.getCommPort(PORT_NAME);

        // 尝试打开串口并设置参数
        if (port.openPort()) {
            try {
                // 设置串口参数
                port.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
                port.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 1000, 0);

                // 获取输出流并发送数据
                OutputStream outputStream = port.getOutputStream();
                outputStream.write(DATA_TO_SEND);
                outputStream.flush();

                log.info("已发送数据: {}", Arrays.toString(DATA_TO_SEND));

            } catch (Exception e) {
                log.error("发送数据时发生错误: {}", e.getMessage());
            } finally {
                port.closePort();  // 发送完数据后关闭串口
            }
        } else {
            log.error("无法打开串口 {}！", PORT_NAME);
        }
    }
}
